#include <stdio.h>
#include <assert.h>

#include "user_threads.h"
#include "user_threads_export.h"
#include "user_io.h"

int global = 0;
int global_pipe[2];

static int start_routine(void * param)
{
	int i;
	for (i=0; i<10; i++) {

		int tmp, val_from_pipe;
		int curr_id = uthread_self();

		tmp = uthread_read(global_pipe[0], &val_from_pipe, sizeof(val_from_pipe));
		assert(sizeof(val_from_pipe) == tmp);

		printf("Thread Id=%d   global=%d   got from pipe %d\n",
			   curr_id ,global, val_from_pipe);

		global++;

		tmp = uthread_write(global_pipe[1], &curr_id, sizeof(curr_id));
		assert(sizeof(curr_id) == tmp);

		uthread_yield();

	}

	return 0;
}

int main()
{
	int tmp;
	tmp = uthread_init();
	assert(UTHREAD_SUCCESS == tmp);

	tmp = uthread_pipe(global_pipe);
	assert(0 == tmp);

	int i;
	for (i=1; i<20; i++){
		tmp = uthread_create(start_routine,NULL);
		assert (tmp == i);
	}

	assert (0 == uthread_self());
	int zero = 0;
	tmp = uthread_write(global_pipe[1], &zero, sizeof(zero));
	assert(sizeof(zero) == tmp);

	uthread_yield();

	start_routine(NULL);

	for (i=1; i<20; i++){
		tmp = uthread_join(i,NULL);
		assert (UTHREAD_SUCCESS == tmp);
	}

	close(global_pipe[0]);
	close(global_pipe[1]);

	return 0;
}
